package api

import (
	"net/http"
	"strconv"

	"gitee.com/LangHuaHuachihua/blog-go/apps/blog"
	"gitee.com/LangHuaHuachihua/blog-go/apps/user"
	"gitee.com/LangHuaHuachihua/blog-go/common"
	"github.com/gin-gonic/gin"
)

func (h *Handler) CreateBlog(c *gin.Context) {

	//从中间件获取对应用户
	v, ok := c.Get(user.AUTH_COOKIE_NAME)
	if !ok {
		common.ReturnReponse(c, "cookce Not Found", 0, http.StatusBadRequest)
	}
	u := v.(*user.User)
	in := blog.NewCreateBlogRequest()
	//直接将数据转为json->到对象上
	err := c.BindJSON(in)
	if err != nil {
		common.ReturnReponse(c, "Request Bad", 0, http.StatusBadRequest)
	}

	in.Author = u.Username
	ins, err := h.svc.CreateBlog(c.Request.Context(), in)
	if err != nil {
		resp := common.NewResponse(c, http.StatusInternalServerError, http.StatusInternalServerError, err.Error())
		c.JSON(http.StatusBadRequest, resp)
		// logger.L().Debug().Msg(err.Error())
		return
	}
	c.JSON(http.StatusOK, ins)
}

func (h *Handler) QueryBlog(c *gin.Context) {
	in := blog.NewQueryBlogRequest()
	//strconv.Atoi asscil -》int
	//page_size=1234&name=Manu&value=
	ps := c.Query("page_size")
	pn := c.Query("page_number")
	if ps != "" {
		in.PageSize, _ = strconv.Atoi(c.Query("page_size"))
	}
	if pn != "" {
		in.PageNumber, _ = strconv.Atoi(c.Query("page_number"))
	}
	in.Author = c.Query("author")
	in.Keywords = c.Query("keywords")

	ins, err := h.svc.QueryBlog(c.Request.Context(), in)
	if err != nil {
		resp := common.NewResponse(c, http.StatusInternalServerError, http.StatusInternalServerError, err.Error())
		c.JSON(http.StatusBadRequest, resp)
		// logger.L().Debug().Msg(err.Error())
		return
	}
	c.JSON(http.StatusOK, ins)
}
